package com.example.showImage;

//import com.example.Main;
import com.example.photoview.*;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.scene.transform.Scale;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 用于控制显示单张图片对应功能的类
 */
public class ImageController implements Initializable {
        //implements Initialize
        //class内fx：id
        @FXML
        private HBox HBox;

        @FXML
        private Button Bigger;

        @FXML
        private Button left90;

        @FXML
        private Button PPT;

        @FXML
        private Button lastBtn;

        @FXML
        private StackPane stkPane;

        @FXML
        private ImageView imgView;

        @FXML
        private Button Del;

        @FXML
        private Button Smaller;

        @FXML
        private Button right90;

        @FXML
        private Button nextBtn;
        /**获取ImageWindow窗口*/
        private Stage stage;
        @FXML
        private  HBox HBox1;

        //private String imageUrl[];//存储资源图片的字符串数组
        //private Image image[]=new Image[];//存储照片的数组
        //private int currentIndex=0;//第几张图片
        public StackPane rootPane;
        private ImageModel imageModel;//imageModel里装着img的信息
        private Image img;//imageView内装img--setimage(img)
        public ArrayList<ImageModel> imageModelArrayList;//存储照片的ArrayList表单
        private SwitchPictures swP;//switchPictures类实例
        private HomeController hc;



        //无参构造方法
        public ImageController() {
        double rotateStatus=0;
        }
//getter

        public void setHBox(javafx.scene.layout.HBox HBox) {
                this.HBox = HBox;
        }

        public Button getBigger() {
                return Bigger;
        }

        public void setBigger(Button bigger) {
                Bigger = bigger;
        }

        public Button getLeft90() {
                return left90;
        }

        public void setLeft90(Button left90) {
                this.left90 = left90;
        }

        public Button getPPT() {
                return PPT;
        }

        public void setPPT(Button PPT) {
                this.PPT = PPT;
        }

        public Button getLastBtn() {
                return lastBtn;
        }

        public void setLastBtn(Button lastBtn) {
                this.lastBtn = lastBtn;
        }

        public StackPane getStkPane() {
                return stkPane;
        }

        public void setStkPane(StackPane stkPane) {
                this.stkPane = stkPane;
        }

        public ImageView getImgView() {
                return imgView;
        }

        public void setImgView(ImageView imgView) {
                this.imgView = imgView;
        }

        public Button getDel() {
                return Del;
        }

        public void setDel(Button del) {
                Del = del;
        }

        public Button getSmaller() {
                return Smaller;
        }

        public void setSmaller(Button smaller) {
                Smaller = smaller;
        }

        public Button getRight90() {
                return right90;
        }

        public void setRight90(Button right90) {
                this.right90 = right90;
        }

        public Button getNextBtn() {
                return nextBtn;
        }

        public void setNextBtn(Button nextBtn) {
                this.nextBtn = nextBtn;
        }

        public void setStage(Stage stage) {
                this.stage = stage;
        }

        public void setRootPane(StackPane rootPane) {
                this.rootPane = rootPane;
        }

        public void setImageModel(ImageModel imageModel) {
                this.imageModel = imageModel;
        }

        public Image getImg() {
                return img;
        }

        public void setImg(Image img) {
                this.img = img;
        }

        public ArrayList<ImageModel> getImageModelArrayList() {
                return imageModelArrayList;
        }

        public void setImageModelArrayList(ArrayList<ImageModel> imageModelArrayList) {
                this.imageModelArrayList = imageModelArrayList;
        }

        public SwitchPictures getSwP() {
                return swP;
        }

        public void setSwP(SwitchPictures swP) {
                this.swP = swP;
        }

        public HomeController getHc() {
                return hc;
        }

        public void setHc(HomeController hc) {
                this.hc = hc;
        }

        public javafx.scene.layout.HBox getHBox() {
                return HBox;
        }

        public ImageModel getImageModel() {
                return imageModel;
        }
        public Stage getStage(){
                return stage;
        }

        public Pane getRootPane() {
                return rootPane;
        }

        /**
         * 先进行
         * 完成类初始化
         */
        //@Override
        public void initialize(URL location, ResourceBundle resources) {
                System.out.println("ImageController -- initialize started");
                ControllerUtil.controllers.put(this.getClass().getSimpleName(), this);
                hc = (HomeController) ControllerUtil.controllers.get(HomeController.class.getSimpleName());
                stage = ImageWindow.getStage();
                System.out.println("ImageWindow -- initialization end");
        }

        /**
         * 后进行
         * 初始化加载图片界面
         */

        public void initImage(ImageModel imM) {
                System.out.println("ImageController -- initImage function start.");
                double widthOfWindow;
                double heightOfWindow;
                //没有图片就结束了
                if (imM == null) {
                        this.imageModel = null;
                        imgView.setImage(null);
                        System.out.println("ImageController -- The image is NULL!");
                        return;
                }

//              排序方式
                if (hc.isComboBoxClicked()) {
                        /**
                         * 使用选择排序方式排序
                         */
                        imageModelArrayList = ImageList.refreshListStr(imM.getImageFile().getParent(), hc.getSortComboBox().getValue());
                } else {
                        /**
                         * 无需排序
                         */
                        imageModelArrayList = ImageList.refreshList(imM.getImageFile().getParent());
                }
//                imageModelArrayList = ImageList.refreshList(image.getImageFile().getParent());
//              初始化内容
                this.imageModel = imM;
                this.img = new Image(imM.getImageFile().toURI().toString());//老师说过的东西
                //System.out.println(imM.getImageFile().toURI().toString());

                this.imgView.setImage(img);//java.lang.NullPointerException--没有new imageView
                //imgView.setRotate(0);//旋转0度
                this.swP = new SwitchPictures(imageModelArrayList);

                imgView.setPreserveRatio(true);//保留图像的高宽比
                imgView.setSmooth(true);//设置smooth属性为真,平滑加载

                //以下转换图片比例，避免一边过大的情况
                //获取当前窗口高度比例

                if (stage != null) {
                        widthOfWindow = stage.getScene().getWidth();
                        heightOfWindow = stage.getScene().getHeight();
                } else {
                        widthOfWindow = Main.width;//Non-static field 'width' cannot be referenced from a static context
                        heightOfWindow = Main.height;
                }

                double systemRatio = widthOfWindow / heightOfWindow;    //窗口长宽比
                double imgRatio = img.getWidth() / img.getHeight();     //图片长宽比

                //清空上次设置后遗留下的数据
                imgView.fitWidthProperty().unbind();
                imgView.fitHeightProperty().unbind();
                imgView.setFitHeight(0);
                imgView.setFitWidth(0);

                //若图片过长或过宽，缩小长度
                if (img.getWidth() > widthOfWindow || img.getHeight() > heightOfWindow) {
                        if (imgRatio > systemRatio) {//不合乎比例
                                //imgView.setFitWidth(rootPane.getWidth()/1.5);
                                imgView.setFitWidth(widthOfWindow/1.2);
                        } else {//以原尺寸显示
                                //imgView.setFitHeight(rootPane.getHeight()/1.5);;//java.lang.NullPointerException
                                imgView.setFitHeight(heightOfWindow/1.2);
                        }
                } else {
                        imgView.setFitWidth(img.getWidth());
                }
//                imgView.fitWidthProperty().setValue(img.getWidth());
                System.out.println("ImageController -- initImage done...");
                //System.out.println("imageModelArrayList content:"+imageModelArrayList);//输出ArrayList中内容
                pushMe();//拖动图片
                scrollOnMouse();//滚轮
        }


        /**
         * 实现拖动图片函数
         * 用二维数组保存鼠标上次点击的位置
         * 使用translate类实现imgView的位置变动
         */

        @FXML
        void pushMe() {
                //记录鼠标点击的每次位置
                final double[] mouseLastPosition = new double[2];
                imgView.setOnMousePressed(new EventHandler<MouseEvent>() {
                        @Override
                        public void handle(MouseEvent event) {
                                mouseLastPosition[0] = event.getX();
                                mouseLastPosition[1] = event.getY();
                        }
                });
                //以下实现鼠标拖拽移动
                imgView.setOnMouseDragged(new EventHandler<MouseEvent>() {
                        @Override
                        public void handle(MouseEvent event) {
                                Translate translate = new Translate(event.getX() - mouseLastPosition[0], event.getY() - mouseLastPosition[1]);
                                imgView.getTransforms().add(translate);
                        }
                });
        }

        /**
         * 鼠标滚轮设置图片大小函数
         * getDeltaY能够获取滚动方向
         */
        @FXML
        void scrollOnMouse(){
                imgView.setOnScroll(new EventHandler<ScrollEvent>() {
                        @Override
                        public void handle(ScrollEvent event) {
                                //如果滚轮向下滑动，缩小
                                if (event.getDeltaY() < 0) {
                                        Scale scale = new Scale(0.9, 0.9, event.getX(), event.getY());
                                        imgView.getTransforms().add(scale);
                                }
                                //如果滚轮向上滑动，放大
                                if (event.getDeltaY() > 0) {
                                        Scale scale = new Scale(1.1, 1.1, event.getX(), event.getY());
                                        imgView.getTransforms().add(scale);
                                }
                        }
                });
        }

        /**
         * 切换图片都会使用这个函数恢复正常
         */
        @FXML
        private void initStatus() {//初始化图片的缩放比例
                imgView.setRotate(0);//旋转取消
                imgView.setScaleX(1.0);
                imgView.setScaleY(1.0);
                imgView.getTransforms().clear();//
        }

        /**
         * 上一张图片
         * @param
         * @throws IOException
         */
        @FXML
        void lastImg() throws IOException {
                System.out.println("lastImg function start.");
                initStatus();
                //刷新列表
                if(imageModel!=null){
                        imageModelArrayList = ImageList.refreshList(imageModel.getImageFile().getParent());//刷新文件列表
                }
                //检测列表中的内容为空
                if(imageModelArrayList == null || imageModelArrayList.size()==0){
                        initImage(null);
                        System.out.println("imageModelArrayList is null");
                        stage.setTitle("无图片");
                }
                //否则选中上一图片
                else{
                        initImage(swP.lastOne(imageModel));
                        stage.setTitle(imageModel.getImageName()); //更新图片名字
                }
        }

        /**
         * 下一张图片
         * @param
         * @throws IOException
         */
        @FXML
        public void nextImg() throws IOException {
                System.out.println("nextImg function start.");
                initStatus();
                if(imageModel!=null){
                        imageModelArrayList = ImageList.refreshList(imageModel.getImageFile().getParent());//刷新文件列表
                }

                if(imageModelArrayList ==null||imageModelArrayList.size()==0){
                        //snackbar.enqueue(new JFXSnackbar.SnackbarEvent("此文件夹图片已空"));
                        this.imageModel=null;
                        imgView.setImage(null);
                        stage.setTitle("无图片");
                }
                else{
                        initImage(swP.nextOne(imageModel));
                        stage.setTitle(imageModel.getImageName());
                }
        }

        /**
         * 放大
         * @param event
         */
        @FXML
        void big(ActionEvent event) {
                System.out.println("big function start.");
                imgView.setScaleX(imgView.getScaleX() * 1.25);
                imgView.setScaleY(imgView.getScaleY() * 1.25);
        }

        /**
         * 缩小
         * @param event
         */
        @FXML
        void small(ActionEvent event) {
                System.out.println("small function start.");
                imgView.setScaleX(imgView.getScaleX() * 0.75);
                imgView.setScaleY(imgView.getScaleY() * 0.75);
        }


        @FXML
        void setLeft90(ActionEvent e){
                imgView.setRotate(swP.leftSpin());//逆时针旋转90度
                System.out.println("setLeft90 function start.");
        }

        @FXML
        void setRight90(ActionEvent e){
                imgView.setRotate(swP.rightSpin());//顺时针旋转90度
                System.out.println("setRight90 function start.");
        }
//

        /**
         * 幻灯片播放
         */
        @FXML
        public void showUp() {
                showUpPacked();
        }
        int result=0;
        private void showUpPacked(){
                System.out.println("Showup function start.");
                initStatus();   //比例重新设定
                HBox.setVisible(false);  //使工具栏不可见
                HBox1.setVisible(false);
                stage.setFullScreen(true);  //设置窗口为全屏
                //snackbar.enqueue(new JFXSnackbar.SnackbarEvent("开始幻灯片放映，点击任意键结束"));

                //以下实现定时器功能翻页

                Timer timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                                //定时任务中安排切换下一页功能
                                Platform.runLater(() -> {
                                        try {
                                                nextImg_NoAlert();
                                        } catch (IOException e) {
                                                e.printStackTrace();
                                        }
                                });
                        }
                }, 2500, 2500); // 定时器执行


                //当鼠标点击退出
                imgView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                        @Override
                        public void handle(MouseEvent event) {
                                System.out.println("end by click");leaveAway(timer, stage);
                        }
                });

                //键盘输入任意键退出
                imgView.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
                        @Override
                        public void handle(KeyEvent event) {
                                System.out.println("end by key");leaveAway(timer, stage);
                        }
                });
        }

        private void leaveAway(Timer timer, Stage stage){
                System.out.println("leave away function start.");

                timer.cancel();//取消时间任务
                HBox.setVisible(true);//显示框
                HBox1.setVisible(true);
                stage.setFullScreen(false);//取消全屏
                stage.sizeToScene();//动态切换fxml文件
                //snackbar.enqueue(new JFXSnackbar.SnackbarEvent("幻灯片放映结束"));

                //清空事件
                imgView.getScene().setOnKeyPressed(event -> {
                });
                imgView.setOnMouseClicked(event -> {
                });
        }

        public void nextImg_NoAlert() throws IOException {
                System.out.println("nextImg function start.");
                initStatus();
                if(imageModel!=null){
                        imageModelArrayList = ImageList.refreshList(imageModel.getImageFile().getParent());//刷新文件列表
                }

                if(imageModelArrayList ==null||imageModelArrayList.size()==0){
                        this.imageModel=null;
                        imgView.setImage(null);
                        stage.setTitle("无图片");
                }
                else{
                        initImage(swP.nextOne_NoAlert(imageModel));
                        stage.setTitle(imageModel.getImageName());
                }
        }
}

